"""
项目 App
"""

from contextlib import asynccontextmanager

from fastapi import FastAPI

import utils.enum_utils as enum
from components.exception import register_exception_handlers
from components.middleware import register_middleware
# from components.monitor import add_logfire_monitor
from components.open_api import get_openapi_tags
from components.route import update_route
from ex.urls import register_router
from utils.data_utils.gen import custom_generate_unique_id


@asynccontextmanager
async def app_lifespan(app: FastAPI):
    """ FastAPI 应用的生命周期管理 """

    from components.logger import log
    from components.thread_pool import shutdown_thread_pools

    log.success("[FastAPI 生命周期]项目启动")

    yield

    log.success("[FastAPI 生命周期]项目停止")

    shutdown_thread_pools()  # 优雅地关闭所有线程池


def create_application() -> FastAPI:
    # 等待其他组件启动完成
    app: FastAPI = FastAPI(
        title="EX",
        description="EX API Doc",
        debug=True,
        generate_unique_id_function=custom_generate_unique_id,
        responses={422: {"description": ""}},  # 添加这一行来隐藏 422 响应
        swagger_ui_parameters={
            "syntaxHighlight": {
                "theme": enum.SwaggerUITheme.NORD,
            },
        },
        openapi_tags=get_openapi_tags(),
        lifespan=app_lifespan,
    )
    register_router(app)
    register_exception_handlers(app)
    register_middleware(app)
    update_route(app)
    # add_logfire_monitor(app)

    return app
